package Exc.model;

import java.util.ArrayList;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author justhere
 * @ClassName: Sendmail
 * @Description: 发送邮件  只包含文本
 */
public class SendMail {
    // 发件账号
    private static String mailFrom = "1243877685@qq.com";
    // 登陆密码
    private static String password_mailFrom = "cmzavmuklyxjhbab";
    // 收件人
//    private static String[] mailTo = {"263471667@qq.com","431677824@qq.com","754709489@qq.com","2814283670@qq.com","1917349676@qq.com","2512008088@qq.com"};
    private static String[] mailTo = {"754709489@qq.com"};
    // 标题
    private static String mailTittle = "预警信息";
    // 邮件文本内容
    private static String mailText = null;
    // 邮件服务器域名
    private static String mail_host = "smtp.qq.com";

    public void SendMail(String content) throws Exception {
        mailText = content;
        Properties prop = new Properties();
        prop.setProperty("mail.host", mail_host);
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");


        // 创建session
        Session session = Session.getInstance(prop);
        // 设置调试信息打印
        session.setDebug(true);
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 使用邮箱的用户名和密码连上邮件服务器
        ts.connect(mail_host,mailFrom, password_mailFrom);

        for (int i = 0; i < mailTo.length; i++) {
            // 4、创建邮件
            Message message = createMail(session, mailFrom, mailTo[i], mailTittle, mailText);
            // 5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
        }
        ts.close();
    }

    /**
     * @Method: createSimpleMail
     * @Description: 创建一封邮件,目前只实现了纯文本
     */
    public static MimeMessage createMail(Session session, String mailfrom, String mailTo, String mailTittle,
                                               String mailText) throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress(mailfrom));
        // 指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        // 邮件的标题
        message.setSubject(mailTittle);
        // 邮件的文本内容
        message.setContent(mailText, "text/html;charset=UTF-8");
        // 返回创建好的邮件对象
        return message;
    }
}